// pages/ticket/get/get.js
import {
  TicketModel
} from "../../../models/ticket";
const ticketModel = new TicketModel()
const app = getApp();
let clickAble = true
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showLayer: false,
    tickets: [],
    getTicketAmount: 0,
    rules: [],
    subTitle: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.myLogin().then(res=>{
      wx.hideLoading();
      this.loadTicket()
    })
  },
  loadTicket() {
    ticketModel.loadTicket().then(res => {
      console.log(res)
      this.setData({
        tickets: res,
        subTitle: res[0].des ? res[0].des : ''
      })
      this.loadUseRule('',res[0].id)
    })
  },
  getTicket(e) {
    const d = e.currentTarget.dataset
    if (d.getFlag || d.number <= 1) {
      return 
    }
    if (clickAble) {
      clickAble = false
      app.myLogin().then(res => {
        wx.hideLoading();
        this.getTicketApi(d.ruleId)
      })
    }

  },
  getTicketApi(ruleId) {
    ticketModel.getTicket(ruleId).then(res => {
      clickAble = true
      if (res.amount) {
        this.setData({
          getTicketAmount: res.amount,
          showLayer: true,
        })

        this.loadTicket()
      }
    })
  },
  closeLayer() {
    this.setData({
      showLayer: false
    })
  },
  goUse() {
    const from = app.globalData.from
    console.log(from)
    if (from == 'pages/confirm/confirm') {
      wx.redirectTo({
        url: '/pages/confirm/confirm'
      })
    }else{
      app.toMayi()
    }
  },
  loadUseRule(couponId,ruleId) {
    ticketModel.loadUseRule(couponId,ruleId).then(res => {
      console.log(res)
      this.setData({
        rules: res
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      showLayer: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})